use neon::prelude::*;
use neon::register_module;
use std::collections::VecDeque;

/// 分割字符串
fn split_string(string: String) -> Vec<String> {
    let len = string.len();
    let string = string.get(1..(len - 1)).unwrap();
    let mut vec: VecDeque<&str> = string.split(',').collect::<VecDeque<&str>>();
    let hi = f32::log2(vec.len() as f32);


    // 进行逻辑处理
    let mut result = vec![""; (1 << (hi as usize + 1)) - 1];
    println!("result size {}", result.len());
    result[0] = vec.pop_front().unwrap();
    let mut i = 1;
    while i < result.len() {
        let parent = i / 2;
        if vec.is_empty() {
            break;
        }
        if result[parent] != "" {
            let val = vec.pop_front().unwrap();
            if val == "null" {
                result[i] = "";
            } else {
                result[i] = val;
            }
        }
        i += 1;
    }

    result.into_iter().map(|s| s.to_string()).collect()
}


/// 解析输入，转换一个棵树
/// 树的返回是一个string数组
fn handle_tree_string_input(mut cx: FunctionContext) -> JsResult<JsArray> {
    // 输入字符串
    let string = cx.argument::<JsString>(0)?.value();
    let vec = split_string(string);
    let js_array = JsArray::new(&mut cx, vec.len() as u32);
    vec.into_iter().enumerate().for_each(|(i, s)| {
        let js_string = cx.string(s);
        let _ = js_array.set(&mut cx, i as u32, js_string);
    });
    Ok(js_array)
}


register_module!(mut m, {
    m.export_function("handleTreeStringInput", handle_tree_string_input)?;
    Ok(())
});

mod test {

    #[test]
    fn split_string_test() {
        let string = "[3,5,1,6,2,0,8,null,null,7,4]";
        let vec = crate::split_string(string.to_string());
        vec.iter().for_each(|a| {
            print!("{} ", a);
        });
        let mut result = vec![];
        result.push(String::from("3"));
        result.push(String::from("5"));
        result.push(String::from("1"));
        result.push(String::from("6"));
        result.push(String::from("2"));
        result.push(String::from("0"));
        result.push(String::from("8"));
        result.push(String::from(""));
        result.push(String::from(""));
        result.push(String::from("7"));
        result.push(String::from("4"));
        result.push(String::from(""));
        result.push(String::from(""));
        result.push(String::from(""));
        result.push(String::from(""));
        assert_eq!(vec, result);
    }
}
